<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
    <h1>这是index1页面</h1>
    <input type="text" placeholder="用户名称">
    <button class="conncet">连接</button>
    <button class="to">发送</button>

    <script>
        var conncetion = null;
        $('.conncet').click(function () {
            var user = $('input').val();
            // 当conncetion 有值的时候，直接结束代码运行
            if (conncetion) return;
            //建立连接
            // 获取一个连接对象
            conncetion = new WebSocket('ws://192.168.21.249:3000/' + user)
            conncetion.onopen = function () {

                console.log('连接成功')
            }
            conncetion.onerror = function () {
                console.log('连接失败')
            }

            conncetion.onmessage = function (res) {
                var obj = JSON.parse(res.data);
                console.log(obj);
            }
        })

        $('.to').click(function () {
            var text = $('textarea').val();

            if(!conncetion){
                alert('没有连接');
                return;
            };

            var obj = {data:text};
            conncetion.send(JSON.stringify(obj));

        })
     
    </script>
</body>

</html>